<template>
  <div class="page-model">
    <el-dialog :title="modelConfig.title" v-model="dialogVisible" width="30%" destroy-on-close center>
      <i-form ref="IFormRef" v-model="formData" v-bind="modelConfig" @validPass="validPass" />
      <slot></slot>
      <template #footer class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirmClick">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import IForm from '@/base-ui/form/index'
import { useStore } from '@/store'
export default defineComponent({
  components: { IForm },
  props: {
    modelConfig: {
      type: Object,
      required: true
    },
    defaultInfo: {
      type: Object,
      default: () => ({})
    },
    otherInfo: {
      type: Object,
      default: () => ({})
    },
    pageName: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const dialogVisible = ref(false)
    const formData = ref({})
    watch(
      () => props.defaultInfo,
      (newValue) => {
        for (const item of props.modelConfig.formItems) {
          formData.value[`${item.filed}`] = newValue[`${item.filed}`]
        }
      }
    )
    const store = useStore()
    const IFormRef = ref<InstanceType<typeof IForm>>()
    // 确认新增或编辑
    const handleConfirmClick = () => {
      IFormRef.value.validateFn()
    }
    const validPass = () => {
      dialogVisible.value = false
      if (Object.keys(props.defaultInfo).length) {
        // 编辑
        store.dispatch('system/editPageDataAction', {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id
        })
      } else {
        // 新增
        store.dispatch('system/createPageDataAction', {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo }
        })
      }
    }
    return {
      dialogVisible,
      formData,
      handleConfirmClick,
      IFormRef,
      validPass
    }
  }
})
</script>
<style lang="less" scoped></style>
